const express = require('express')
const model = require('../mongooseData/model/model')
const router = express.Router()
router.post("/register", async(req, res) => {
    const { email, username, psd } = req.body;
    try{
      await model.create({
          email,
          username,
          psd
      })
      res.redirect('http://localhost:3000/login.html')
    }
    catch(err){
        res.send('注册失败')
    }
  });
router.post("/login", async(req, res) => {
    const {email,psd} = req.body
    const user = await model.findOne({email,psd})
    if(user) {
      res.cookie('user',user.username,{
        maxAge: 1000*60,       //设置cookie过期时间为 60秒
})  
        res.redirect(`http://localhost:3000/?username=${user.username}`)
    }else {
        res.send('用户名密码不正确')
    }
  });
  router.get('/',(req,res)=>{
    const {user} = req.cookies
    const {username} = req.query
    if(user){
    res.render('index',{username})

    }else{
      res.redirect('http://localhost:3000/login')
    }
})
  module.exports = router